package com.tianjipms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianjipms.dao.VehicleMapper;
import com.tianjipms.dto.UserVehicleDTO;
import com.tianjipms.entity.Vehicle;
import com.tianjipms.service.VehicleService;
import com.tianjipms.utils.Result;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
@Transactional
public class VehicleServiceImpl extends ServiceImpl<VehicleMapper, Vehicle> implements VehicleService {
    @Resource
    private VehicleMapper vehicleMapper;

    //车牌是否存在
    @Override
    public boolean existsByLicenseNumber(String licenseNumber) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("license_number", licenseNumber);
        return vehicleMapper.exists(queryWrapper);
    }

    @Override
    public IPage<Vehicle> findVehiclListByPage(IPage<Vehicle> page, Long userId) {
        QueryWrapper<Vehicle> queryWrapper = new QueryWrapper<Vehicle>();
        queryWrapper.like(!ObjectUtils.isEmpty(userId),"user_id", userId);
        return vehicleMapper.selectPage(page, queryWrapper);
    }

    @Override
    public Result updateUserByLicenseNumber(UserVehicleDTO vehicleDTO) {
        Vehicle vehicle = vehicleMapper.vehiclByLicenseNumber(vehicleDTO.getLicenseNumber());
        if(vehicle.getUserId() == 0){
            vehicle.setUserId(vehicleDTO.getUserId());
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("license_number",vehicleDTO.getLicenseNumber());
            vehicleMapper.update(vehicle,queryWrapper);
        }else {
            return Result.error();
        }
        return Result.ok();
    }

    @Override
    public Vehicle findVehiclByLicenseNumber(String licenseNumber) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("license_number", licenseNumber);
        return vehicleMapper.selectOne(queryWrapper);
    }
}
